<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
namespace App\Service;

use App\Constants\ErrorCode;
use App\Exception\BusinessException;
use App\Service\Redis\SmsCollection;
use Gregwar\Captcha\CaptchaBuilder;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Redis\Redis;
use Hyperf\Utils\Str;
use HyperfX\Utils\Service;

class SmsService extends Service
{
    /**
     * @Inject
     * @var Redis
     */
    protected $redis;

    /**
     * @Inject
     * @var SmsCollection
     */
    protected $col;

    public function captcha(string $id)
    {
        $code = Str::random(4);
        $this->col->setCaptcha($id, $code);

        $builder = new CaptchaBuilder();
        $builder->setPhrase($code);
        $builder->build();

        return $builder->get();
    }

    public function checkCaptcha(string $id, string $captcha): bool
    {
        return $this->col->getCaptcha($id) === $captcha;
    }

    /**
     * @param $input = [
     *     'mobile' => '18678010000', // 手机号
     *     'id' => '123', // 图片ID
     *     'captcha' => '', // 图片验证码
     * ]
     */
    public function send(array $input): bool
    {
        if (! $this->checkCaptcha($input['id'], $input['captcha'])) {
            throw new BusinessException(ErrorCode::CAPTCHA_INVALID);
        }

        $code = (string) rand(1000, 9999);
        $code = 6666;
        // TODO: 发送验证码
        $this->col->set($input['mobile'], $code, 60 * 5);

        return true;
    }

    /**
     * 判断验证码是否合法.
     */
    public function checkCode(string $mobile, string $code): bool
    {
        return $code === $this->col->get($mobile);
    }
}
